﻿using System;
using System.Collections.Generic;
using System.Dynamic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using FineUI;
using Newtonsoft.Json;
using ZHDJ.Core;
using ZHDJ.Core.Util;
using ZHDJ.Data;
using ZHDJ.Data.DataCaching;
using ZHDJ.Data.Models.Common;

namespace ZHDJ.WebPage
{
    /// <summary>
    /// 
    /// </summary>
    public class UpFileBusiness
    {


        /// <summary>
        /// 上传
        /// </summary>
        /// <param name="fileUpload">上传控件</param>
        /// <param name="createBy">创建人</param>
        /// <param name="description">文件描述</param>
        /// <param name="fileType">文件类型</param>
        /// <returns></returns>
        public static UpFileResult Upload(FileUpload fileUpload, string createBy, string description = "",
            SysEnum.UploadFileType fileType = SysEnum.UploadFileType.uploadfile)
        {
            UpFileResult result = new UpFileResult()
            {
                IsSuccess = false,
                Message = "请选择上传文件"
            };
            if (!fileUpload.HasFile)
            {
                return result;
            }

            if (fileType == SysEnum.UploadFileType.uploadimage)
            {
                bool flag = false;
                string[] fileTypeArray = { ".jpg", ".gif", ".jpeg", ".png" };
                string extension = Path.GetExtension(fileUpload.FileName);//扩展名
                foreach (string item in fileTypeArray)
                {
                    if (item == extension)
                        flag = true;
                }
                if (!flag)
                {
                    result.IsSuccess = false;
                    result.Message = "请上传.jpg|.gif|.jpeg|.png格式的图片";
                    return result;
                }
            }

            result = Upload(fileUpload.PostedFile.InputStream, fileUpload.FileName,
                    createBy, description);
            return result;

        }


        /// <summary>
        /// 上传
        /// </summary>
        /// <param name="fileUpload">HttpPostedFile</param>
        /// <param name="createBy">创建人</param>
        /// <returns></returns>
        public static UpFileResult Upload(HttpPostedFile fileUpload, string createBy, string description = "")
        {

            UpFileResult result = new UpFileResult()
            {
                IsSuccess = false,
                Message = "请选择上传文件"
            };
            if (fileUpload == null)
            {
                return result;
            }
            result = Upload(fileUpload.InputStream, fileUpload.FileName, createBy,
                description);
            return result;

        }

        public static UpFileResult Upload(byte[] byteStream, string fileName, string createBy,
            string description = "")
        {
            var url = GetUpLoadUrl();
            return Upload(url, StreamHelper.ByteToStream(byteStream), fileName, createBy, description);
        }
        public static UpFileResult Upload(Stream memoryStream, string fileName, string createBy,
            string description = "")
        {
            var url = GetUpLoadUrl();
            return Upload(url, memoryStream, fileName, createBy, description);
        }

        public static UpFileResult Upload(string url, Stream memoryStream, string fileName, string createBy, string description = "")
        {
            UpFileResult result = new UpFileResult()
            {
                IsSuccess = false,
                Message = "请选择上传文件"
            };
            using (var DB = new DBInstance().DB)
            {
                var file = HttpRequestBusiness.HttpUploadFile(url, StreamHelper.ToMemoryStream(memoryStream), fileName);
                dynamic json = new ExpandoObject();
                json = JsonConvert.DeserializeObject<ExpandoObject>(file);
                var save = 0;
                PartyFile partyFiles;
                if (json.state == "SUCCESS")
                {
                    partyFiles = new PartyFile();
                    partyFiles.CreateBy = createBy;
                    partyFiles.CreateTime = DateTime.Now;
                    partyFiles.Description = description;
                    partyFiles.Url = json.url.Replace("../../../", "");
                    partyFiles.Size = (int)(memoryStream.Length / 1024);
                    partyFiles.Title = json.title;
                    partyFiles.ID = StringHelper.NewID;
                    partyFiles.Extension = Path.GetExtension(json.title);
                    DB.PartyFiles.Add(partyFiles);
                    save = DB.SaveChanges();
                    result.FileUrl = partyFiles.Url;
                    result.FileTitle = partyFiles.Title;
                    result.FileID = partyFiles.ID;
                }
                result.Message = json.state;
                result.IsSuccess = json.state == "SUCCESS" && save > 0;

                return result;
            }
        }

        /// <summary>
        /// 获取上传路径
        /// </summary>
        /// <param name="fileType">文件种类</param>
        /// <returns></returns>
        private static string GetUpLoadUrl(SysEnum.UploadFileType fileType = SysEnum.UploadFileType.uploadfile)
        {
            var url = "";
            var action = fileType.ToString();
            var uploadFileUrl = SystemParameterCaching.Get(SystemParameterKey.UploadFileUrl);

            if (!string.IsNullOrEmpty(uploadFileUrl))
                url = uploadFileUrl + "?action=" + action;
            else
            {
                var webHost = SystemParameterCaching.Get(SystemParameterKey.WebHost);
                url = webHost +
                      "/Resource/ueditor/net/controller.ashx?action=" + action;
            }
            return url;
        }



        /// <summary>
        /// 获取文件url
        /// </summary>
        /// <param name="fileId"></param>
        /// <param name="isSmall">是否小图</param>
        /// <returns></returns>
        public static string GetFileUrl(string fileId, bool isSmall = false)
        {
            using (var DB = new DBInstance().DB)
            {
                var url = "";
                var file = DB.PartyFiles.Find(fileId);
                if (file == null)
                {
                    return "";
                }
                var sysPara = SystemParameterCaching.Get(SystemParameterKey.UploadFileHost);
                if (!string.IsNullOrEmpty(sysPara))
                {
                    url = sysPara + "/" + file.Url;
                }
                else
                {
                    url = file.Url;
                }
                if (isSmall)
                {
                    var e = Path.GetExtension(url) ?? "null";
                    url = url.Replace(e, "_small" + e);
                }
                return url;
            }
        }

        /// <summary>
        /// 格式化上传文件路径
        /// </summary>
        /// <param name="fileUrl">文件上传路径（相对）</param>
        /// <param name="isSmall">是否小图</param>
        /// <returns></returns>
        public static string FormatFileUrl(string fileUrl, bool isSmall = false)
        {
            using (var DB = new DBInstance().DB)
            {
                var url = "";
                if (string.IsNullOrEmpty(fileUrl) || fileUrl.ToLower().StartsWith("http://"))
                {
                    return fileUrl;
                }
                var webHost = SystemParameterCaching.Get(SystemParameterKey.UploadFileHost);
                if (fileUrl.StartsWith("/"))
                {
                    url = webHost + fileUrl;
                }
                else
                {
                    url = webHost + "/" + fileUrl;
                }
                if (isSmall)
                {
                    var e = Path.GetExtension(url);
                    url = url.Replace(e, "_small" + e);
                }
                return url;
            }
        }
        /// <summary>
        /// 获取文件名
        /// </summary>
        /// <param name="fileID"></param>
        /// <returns></returns>
        public static string GetFileName(string fileID)
        {
            using (var DB = new DBInstance().DB)
            {
                var url = "";
                var file = DB.PartyFiles.Find(fileID);
                if (file == null)
                {
                    return "";
                }
                return file.Title;
            }
        }
    }

    /// <summary>
    /// 上传结果
    /// </summary>
    public class UpFileResult
    {
        public UpFileResult()
        {
            IsSuccess = false;
            FileID = "";
            FileUrl = "";
            Message = "";
            FileTitle = "";
        }

        /// <summary>
        /// 是否上传成功
        /// </summary>
        public bool IsSuccess { get; set; }
        /// <summary>
        /// 上传成功后的文件id
        /// </summary>
        public string FileID { get; set; }
        /// <summary>
        /// 上传成功后的文件地址（不带域名）
        /// </summary>
        public string FileUrl { get; set; }

        /// <summary>
        /// 上传结果信息
        /// </summary>
        public string Message { get; set; }

        public string FileTitle { get; set; }
    }
}
